package server

import (
	"go.manyji.com/lib/log"
	"strings"
)

var (
	roles    = []*Role{}
	rolePerm = map[string]map[string]bool{}
)

type Role struct {
	Id    int
	Name  string
	Perms []string
}

func init() {
	AfterDbOpen(func() {
		if err := loadRoles(); err != nil {
			log.Fatal(err)
		}
		if err := loadUsers(); err != nil {
			log.Fatal(err)
		}
	})
}

func loadRoles() error {
	rows, err := db.Query("SELECT `id`,`Name`,`Perms` FROM `app_role`")
	if err != nil {
		return err
	}
	defer rows.Close()
	list := []*Role{}
	rpm := map[string]map[string]bool{}
	for rows.Next() {
		role := &Role{Perms: []string{}}
		perms := ""
		if err := rows.Scan(&role.Id, &role.Name, &perms); err != nil {
			return err
		}
		if perms != "" {
			role.Perms = strings.Split(perms, "|")
		}
		list = append(list, role)
		rp := map[string]bool{}
		for _, p := range role.Perms {
			rp[p] = true
		}
		rpm[role.Name] = rp
	}
	roles = list
	rolePerm = rpm
	return nil
}

func GetRoles() []*Role {
	list := []*Role{}
	for _, row := range roles {
		role := &Role{Id: row.Id, Name: row.Name, Perms: make([]string, len(row.Perms))}
		copy(role.Perms, row.Perms)
		list = append(list, role)
	}
	return list
}

func SetRolePerms(id int, perms []string) error {
	if _, err := db.Exec("UPDATE `app_role` SET `Perms`=? WHERE `id`=?", strings.Join(perms, "|"), id); err != nil {
		return err
	}
	return loadRoles()
}

func addRole(name string) error {
	if _, err := db.Exec("INSERT INTO `app_role` (`Name`,`Perms`) VALUES (?,?)", name, ""); err != nil {
		return err
	}
	return loadRoles()
}
